<?php

	include_once("parser.php");
	
	class FacebookParser extends Parser{
		
		public $url = "";
		private $username = "";
		private $password = "";
		public $numberOfPosts = 20;
		
		
		//Should set a default url
		function __construct($user, $pass) {
			parent::__construct();
			$this->password = $pass;
			$this->username = $user;
		}
		//script provided by facebook.com
		function cURL($url, $header=NULL, $cookie=NULL, $p=NULL)
		{
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_HEADER, $header);
			curl_setopt($ch, CURLOPT_NOBODY, $header);
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_COOKIE, $cookie);
			curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

			if ($p) {
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $p);
			}
			$result = curl_exec($ch);

			if ($result) {
				return $result;
			} else {
				return curl_error($ch);
			}
			curl_close($ch);
		}

		
		function scrapePosts() {
			//using out cURL get the raw html of the facbookmainpage
			$cookie;
			$a = $this->cURL("https://login.facebook.com/login.php?login_attempt=1",true,null,"email=$this->username&pass=$this->password");
			preg_match('%Set-Cookie: ([^;]+);%',$a,$b);
			$c = $this->cURL("https://login.facebook.com/login.php?login_attempt=1",true,$b[1],"email=$this->username&pass=$this->password");
			preg_match_all('%Set-Cookie: ([^;]+);%',$c,$d);
			for($i=0;$i<count($d[0]);$i++)
				@$cookie.=$d[1][$i].";";
				
			$page_html =  $this->cURL("https://www.facebook.com/",null,$cookie,null);
		//	echo htmlspecialchars($page_html);
			
		$dom = new domDocument;
		@$dom->loadHTML($page_html);
		$dom->preserveWhiteSpace = true;
		$finder = new DomXPath($dom);
		$classname = " thing id-t3";
		
		//queries to get the data in the html
		$threads = $finder->query("//ul[@id='home_stream']");
		$images = $finder->query("//ul[@id='home_stream']");
		$replys = $finder->query("//ul[@id='home_stream']");
		$nodeNo = $threads->length;
		echo $nodeNo;
		$posts = array();
		for($i=0; $i<$nodeNo; $i++) {
			$post = new Post();
			$post->rank = ($i+1);
			echo $threads->item($i)->nodeValue . '<br>';
		}
		return $posts;
		}
	}
	//for testing should be removed when ready
	$parser = new FacebookParser("USERNAME","PASSWORD");
	$posts = $parser->scrapePosts();
?>